const mongoose = require('mongoose')
const db = 'mongodb://localhost/preview'
mongoose.Promise = global.Promise
exports.connect = () => {

  let maxConnectTimes = 0

  return new Promise((resolve, reject) => {

    if (process.env.NODE_ENV !== 'production') {
      mongoose.set('debug', true)
    }

    mongoose.connect(db)

    mongoose.connection.on('disconnected', () => {
      maxConnectTimes++
      if (maxConnectTimes < 5) {
        mongoose.connect(db)
      } else {
        throw new Error('mogoDB is dead!')
      }
    })

    mongoose.connection.on('error', () => {
      maxConnectTimes++
      if (maxConnectTimes < 5) {
        mongoose.connect(db)
      } else {
        throw new Error('mogoDB is dead!')
      }
    })

    mongoose.connection.on('open', () => {
      const Dog = mongoose.model('Dog', {
        name: String
      })
      const doga = new Dog({
        name: '阿尔法'
      })

      doga.save().then(() => {
        console.log('wang')
      })

      resolve()
      console.log('MongoDB Connectd successfully!');
    })
  })

}